package com.apps.ftapp.activity;

import android.os.Bundle;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ViewFlipper;

import com.apps.ftapp.R;
import com.apps.ftapp.adapter.QuestionReportAdapter;
import com.apps.ftapp.adapter.Singleton;
import com.apps.ftapp.model.CuoTiAllModel;
import com.apps.ftapp.model.Question;
import com.apps.ftapp.model.SubjectResultModel;
import com.apps.ftapp.util.ActivitySkipUtil;
import com.apps.ftapp.util.Async;
import com.apps.ftapp.util.Constant;
import com.apps.ftapp.util.L;
import com.apps.ftapp.util.Tools;
import com.google.gson.Gson;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import cz.msebera.android.httpclient.Header;
import es.dmoral.toasty.Toasty;

public class CuotiAllActivity extends BaseActivity implements GestureDetector.OnGestureListener, View.OnClickListener {

    @BindView(R.id.viewFlipper)
    ViewFlipper mViewFlipper;

    //1.定义手势检测器对象
    GestureDetector mGestureDetector;
    //2.定义一个动画数组，用于为ViewFilpper指定切换动画效果。
    Animation[] animations = new Animation[4];
    //3.定义手势两点之间的最小距离
    final int FLIP_DISTANCE = 50;

    List<Question> mQuestion = new ArrayList<>();
    QuestionReportAdapter adapter;
    @BindView(R.id.jindu)
    TextView jindu;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.types)
    TextView types;


    private int cur = 1; //当前题


    private String[] danci = {"A", "B", "C", "D", "E", "F"};

    private String id;


    private Gson gson = new Gson();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_error_detail);
        ButterKnife.bind(this);

        setTitle("");
        commTitle.setVisibility(View.GONE);

        //新页面接收数据
        Bundle bundle = this.getIntent().getExtras();
        //接收name值
        id = bundle.getString("id");


        Log.i("main", "::::" + id);
        initView();

    }


    private void initView() {
        //1.构建手势检测器
        mGestureDetector = new GestureDetector(this, this);
        //2准备数据
        // List<Question> questions = initData(id);
        initData(id);


    }

    private View addQuestionView(final Question question) {
        View view = View.inflate(this, R.layout.activity_chnihealthreport, null);
        TextView tes = view.findViewById(R.id.tv_question);
        ListView listview = view.findViewById(R.id.lv_question_answer);
        adapter = new QuestionReportAdapter(this, question);
        listview.setAdapter(adapter);
        tes.setText(question.getQuestion());
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                TextView t = view.findViewById(R.id.biao);

                if (cur == mQuestion.size()) {

                } else {

                    mViewFlipper.setInAnimation(animations[0]);
                    mViewFlipper.setOutAnimation(animations[1]);
                    mViewFlipper.showNext();
                }
                t.setBackgroundResource(R.drawable.yuan1);
                jindu.setText(cur + "");

            }
        });
        return view;
    }


    public void tijiao() {


        Singleton s = Singleton.getInstance();
        L.i("main", s.getStartTime());
        L.i("main", Tools.getTime());
        L.i("main", s.getId());
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("id", s.getId());
        params.put("beginTime", s.getStartTime());
        params.put("endTime", Tools.getTime());
        params.put("Answers", s.getDatas());
        params.put("usedTime", 10);
        Async.post("tiku/finish", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    // ActivitySkipUtil.skipAnotherActivity(GestureFilpActivity.this,SubjectResultActivity.class,true);

                    SubjectResultModel result = gson.fromJson(new String(responseBody), SubjectResultModel.class);
                    if (1 == Tools.isIntNull(result.getSuccess())) {

                        ActivitySkipUtil.skipAnotherActivity(CuotiAllActivity.this, SubjectResultActivity.class, true);

                    } else {

                        Toasty.normal(getApplicationContext(), result.getError()).show();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

    @Override
    public boolean onDown(MotionEvent e) {
        return false;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent e) {
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        return false;
    }

    @Override
    public void onLongPress(MotionEvent e) {

    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        if (e2.getX() - e1.getX() > FLIP_DISTANCE) {
            if (mViewFlipper.getDisplayedChild() == 0) {
                mViewFlipper.stopFlipping();

                Toasty.normal(getApplicationContext(), "第一个题").show();
                return false;
            } else {
//                mViewFlipper.setInAnimation(animations[2]);
//                mViewFlipper.setOutAnimation(animations[3]);
//                mViewFlipper.showPrevious();
                return false;
            }
        } else if (e1.getX() - e2.getX() > FLIP_DISTANCE) {
            if (mViewFlipper.getDisplayedChild() == mQuestion.size() - 1) {

                Toasty.normal(getApplicationContext(), "最后一个题").show();
                mViewFlipper.stopFlipping();
                return false;
            } else {
                mViewFlipper.setInAnimation(animations[0]);
                mViewFlipper.setOutAnimation(animations[1]);
                mViewFlipper.showNext();
                return true;
            }
        }
        return false;
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //将Activity上的触发的事件交个GestureDetector处理
        return this.mGestureDetector.onTouchEvent(event);
    }


    private void initData(String id) {

        //
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("paperResultId", id);
        L.i("main", "token:::" + Constant.token + ":::" + Constant.uid + ":::" + id);
        Async.post("test/result/all", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    List<Question> questions = new ArrayList();
                    CuoTiAllModel result = new CuoTiAllModel();
                    Singleton singleton = Singleton.getInstance();
                    boolean success = true;
                    try {
                        result = gson.fromJson(new String(responseBody), CuoTiAllModel.class);
                    } catch (Exception e) {
                        e.printStackTrace();
                        success = false;
                    }
                    if (success) {
                        int j = 1;
                        for (CuoTiAllModel.ItemsBean d : result.getItems()) {
                            CuoTiAllModel.ItemsBean.QuestionBean ques = d.getQuestion();
                            Question q1 = new Question();
                            q1.setQuestion(Tools.delHTMLTag(ques.getStem()));
                            List<Question.Answer> mA = new ArrayList<>();
                            int awer = Tools.isIntNull(ques.getAnswer().get(0));
                            int i = 0;
                            for (String str : ques.getMetas().getChoices()) {
                                Question.Answer a1 = new Question.Answer();
                                a1.setAnswerMessage(Tools.delHTMLTag(str));
                                a1.setAnswerCode(danci[i]);
                                a1.setId(d.getId());
                                if (awer == i) {
                                    a1.setIsTrue("1");
                                } else {
                                    a1.setIsTrue("0");
                                }
                                //判断是否正确
                                mA.add(a1);
                                i++;
                            }

                            q1.setSizes(mA.size());
                            mA.add(new Question.Answer());
                            //
                            q1.setJiexi(d.getQuestion().getAnalysis());

                            //加一条答案
                            Question.Personal p = new Question.Personal();
                            p.setDoCount(d.getPersonal().getDo_count());
                            p.setRightCount(d.getPersonal().getRight_count());
                            p.setWrongCount(d.getPersonal().getWrong_count() + "");

                            Question.All all = new Question.All();
                            all.setDoCount(d.getAll().getDo_count());
                            all.setEasyWrong(d.getAll().getEasy_wrong());
                            all.setWrongRate(d.getAll().getWrong_rate());

                            q1.setAll(all);
                            q1.setPersonal(p);
                            q1.setDaan(d.getAnswer_compare());

                            q1.setAnswer(mA);

//                            L.i("main","-----------"+mA.size());

                            questions.add(q1);


                            Map tmap = new HashMap();
                            tmap.put("index", j);
                            tmap.put("name", Tools.delHTMLTag(ques.getStem()));
                            tmap.put("is", false);
                            singleton.addD(tmap);

                            j++;
                        }


                        mQuestion.addAll(questions);
                        jindu.setText(cur + "");
                        total.setText("/" + mQuestion.size() + "");
                        singleton.setStartTime(Tools.getTime());
                        singleton.setId(result.getId());
                        L.i("main", mQuestion.toString());
                        //3.为ViewFilpper添加子控件。
                        for (int i = 0; i < mQuestion.size(); i++) {
                            Question question = mQuestion.get(i);
                            mViewFlipper.addView(addQuestionView(question));
                        }
                        //4.初始化Animation数组
                        animations[0] = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.left_in);
                        animations[1] = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.left_out);
                        animations[2] = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_in);
                        animations[3] = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_out);


                    } else {

                        Map map = gson.fromJson(new String(responseBody), Map.class);

                        Toasty.normal(getApplicationContext(), Tools.isNull(map.get("error"))).show();
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });


    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.shoucang:

                sc();
                break;

            case R.id.timu:
                ActivitySkipUtil.skipAnotherActivity(CuotiAllActivity.this, GestureFilpSucActivity.class, false);
                break;
        }
    }

    /**
     * 收藏
     */
    private void sc() {
        RequestParams params = new RequestParams();
        params.put("token", Constant.token);
        params.put("userId", Constant.uid);
        params.put("question_id", id);
        params.put("targetType", id);
        params.put("targetId", id);
        Async.post("question/favorite", params, new AsyncHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
                if (statusCode == 200) {
                    L.i("main", new String(responseBody));
                    try {
                        //请求成功
                        Map jsonBean = gson.fromJson(new String(responseBody), Map.class);
                        L.i("main", jsonBean.toString());
                        if (1 == Tools.isIntNull(jsonBean.get("success"))) {
                            Toasty.normal(getApplicationContext(), "收藏成功").show();
                            shoucang.setImageDrawable(getResources().getDrawable(R.drawable.f_lx_2_2));
                        } else {
                            Toasty.normal(getApplicationContext(), Tools.isNull(jsonBean.get("error"))).show();
                        }

                    } catch (Exception e) {

                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {

            }
        });
    }

}
